//
//  newCollectedDataViewViewController.m
//  dataGathering
//
//  Created by apple on 14/12/16.
//  Copyright (c) 2014年 shuili. All rights reserved.
//
#import <AVFoundation/AVFoundation.h>
#import "newCollectedDataViewViewController.h"
#import "AFViewShaker.h"

#import "UIImageView+click.h"


@interface newCollectedDataViewViewController ()
@property (weak, nonatomic) IBOutlet UILabel *typeLabel;
@property (weak, nonatomic) IBOutlet UILabel *idLabel;
@property (weak, nonatomic) IBOutlet UITextField *dataNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *dataDescriptionTextField;
@property (weak, nonatomic) IBOutlet UILabel *dataCollectedTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *dataUserNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *dataRealNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *sameNameAlertLabel;
@property (weak, nonatomic) IBOutlet UIScrollView *imageScrollContainerView;

@property(nonatomic, retain)NSMutableArray *imageArray;
@property(nonatomic, retain)NSMutableArray *imageViewArray;

@property(nonatomic, retain)UIButton *addImageButton;

@end

@implementation newCollectedDataViewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [_typeLabel setText:_type];
    _imageArray = [[NSMutableArray alloc] initWithCapacity:10];
    _imageViewArray = [[NSMutableArray alloc] initWithCapacity:10];
    
    _addImageButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 96, 96)];
    [_addImageButton setImage:[UIImage imageNamed:@"u189.png"] forState:UIControlStateNormal];
    [_addImageButton addTarget:self action:@selector(addImageButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    
    _dataNameTextField.delegate = self;
    _dataDescriptionTextField.delegate =self;
    
    [_dataUserNameLabel setText:[[NSUserDefaults standardUserDefaults] objectForKey:@"username"]];
    [_dataRealNameLabel setText:[[NSUserDefaults standardUserDefaults] objectForKey:@"realname"]];
    
    [self initImageScrollView];
    
    
    // Do any additional setup after loading the view.
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [[currentWorkSetManager sharedInstance] updateCollectedData :_data :[_data name] newName:[_dataNameTextField text] newDescription:[_dataDescriptionTextField text] newImgArray:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshAllCollectedDataOnMapview" object:nil];

}
- (IBAction)backButtonClicked:(id)sender {
    [self removeFromParentViewController];
    [self.view removeFromSuperview];
}


- (void)UzysAssetsPickerController:(UzysAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    __weak typeof(self) weakSelf = self;
    __block int totalCount = 0;

    if([[assets[0] valueForProperty:@"ALAssetPropertyType"] isEqualToString:@"ALAssetTypePhoto"]) //Photo
    {
        [assets enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            ALAsset *representation = obj;
            
            UIImage *img = [UIImage imageWithCGImage:representation.defaultRepresentation.fullResolutionImage
                                               scale:representation.defaultRepresentation.scale
                                         orientation:(UIImageOrientation)representation.defaultRepresentation.orientation];
            
            if(![weakSelf.imageArray containsObject:img]){
                
                
                [weakSelf.imageArray addObject:img];
                UIImageView *imageView = [[UIImageView alloc] initWithImage:img];
                imageView.userInteractionEnabled = YES;
                [imageView canClickIt:YES];
                
                [weakSelf.imageViewArray addObject:imageView];
                imageView.frame = CGRectMake(idx * (96+8), 0, 96, 96);
                [weakSelf.imageScrollContainerView addSubview:imageView];
                totalCount++;
            }
            *stop = NO;
        }];
        
        CGRect newFrame = weakSelf.addImageButton.frame;
        newFrame.origin.x = totalCount * (96+8);
        weakSelf.addImageButton.frame = newFrame;
        
        [weakSelf.imageScrollContainerView setContentSize:CGSizeMake(([_imageViewArray count]+1) * 96 + [_imageViewArray count] * 8, 96)];
        
        [[currentWorkSetManager sharedInstance] updateCollectedData : _data :nil newName:[_dataNameTextField text] newDescription:nil newImgArray:weakSelf.imageArray];
        
        
    }
    else //Video
    {
        ALAsset *alAsset = assets[0];
        
        UIImage *img = [UIImage imageWithCGImage:alAsset.defaultRepresentation.fullResolutionImage
                                           scale:alAsset.defaultRepresentation.scale
                                     orientation:(UIImageOrientation)alAsset.defaultRepresentation.orientation];
       // weakSelf.imageView.image = img;
        
        
        
        ALAssetRepresentation *representation = alAsset.defaultRepresentation;
        NSURL *movieURL = representation.url;
        NSURL *uploadURL = [NSURL fileURLWithPath:[[NSTemporaryDirectory() stringByAppendingPathComponent:@"test"] stringByAppendingString:@".mp4"]];
        AVAsset *asset      = [AVURLAsset URLAssetWithURL:movieURL options:nil];
        AVAssetExportSession *session =
        [AVAssetExportSession exportSessionWithAsset:asset presetName:AVAssetExportPresetMediumQuality];
        
        session.outputFileType  = AVFileTypeQuickTimeMovie;
        session.outputURL       = uploadURL;
        
        [session exportAsynchronouslyWithCompletionHandler:^{
            
            if (session.status == AVAssetExportSessionStatusCompleted)
            {
                NSLog(@"output Video URL %@",uploadURL);
            }
            
        }];
        
    }
}

-(void)showClickedImg:(UITapGestureRecognizer *)sender
{


}

-(void)addImageButtonClicked
{
    UzysAssetsPickerController *picker = [[UzysAssetsPickerController alloc] init];
    picker.delegate = self;
    picker.maximumNumberOfSelectionMedia = 5;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"presentMediaPicker" object:picker];
}

- (void)initImageScrollView
{
    [_imageScrollContainerView setContentSize:CGSizeMake(([_imageViewArray count]+1) * 96 + [_imageViewArray count] * 8, 96)];

    [_imageScrollContainerView addSubview:_addImageButton];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (IBAction)deleteAction:(id)sender {
    

    [[[[currentWorkSetManager sharedInstance] getCurrentWorkSet] collectedDataList] removeObject:_data];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"selectedcollectedDataRemoved" object:nil];

    [[currentWorkSetManager sharedInstance] removeCollectedData:[[[currentWorkSetManager sharedInstance] getCurrentWorkSet] name] :_data];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"collectedDataRemoved" object:nil];
    
    [self removeFromParentViewController];
    [self.view removeFromSuperview];
    
    /*
    
    if([[_dataNameTextField text] compare:@""] == NSOrderedSame){
        AFViewShaker *shaker = [[AFViewShaker alloc] initWithView:_dataNameTextField];
        [shaker shake];
        return;
    }
    if([[_dataDescriptionTextField text] compare:@""] == NSOrderedSame){
        AFViewShaker *shaker = [[AFViewShaker alloc] initWithView:_dataDescriptionTextField];
        [shaker shake];
        return;
    }
    if([[[currentWorkSetManager sharedInstance] getCurrentWorkSet] checkNewCollectedDataName:[_dataNameTextField text]]){
        
        _sameNameAlertLabel.alpha = 0;
        
        [self removeFromParentViewController];
        [self.view removeFromSuperview];
        
        
        
        
    } else {
        _sameNameAlertLabel.alpha = 1;
        AFViewShaker *shaker = [[AFViewShaker alloc] initWithView:_sameNameAlertLabel];
        [shaker shake];
    }
     */
}

@end
